using Microsoft.AspNetCore.Components;
using System.Timers;
using System;

namespace Application.Web.Entry.Pages.Components
{
    public partial class AnnAngleView : ComponentBase, IDisposable
    {
        // 实时时间
        [Parameter]
        public string CurrentTime { get; set; } = "0001年01月01日 00:00:00";
        
        // 定时器
        private System.Timers.Timer? _timer;

        // 大地坐标系参数
        [Parameter]
        public string AzimuthGuide { get; set; } = "0.000";
        [Parameter]
        public string ElevationGuide { get; set; } = "0.000";
        [Parameter]
        public string OffsetA { get; set; } = "0.000";
        
        [Parameter]
        public string AzimuthCurrent { get; set; } = "0.000";
        [Parameter]
        public string ElevationCurrent { get; set; } = "0.000";
        [Parameter]
        public string OffsetE { get; set; } = "0.000";

        // 转台坐标系参数
        [Parameter]
        public string AzimuthCommand { get; set; } = "0.000";
        [Parameter]
        public string ElevationCommand { get; set; } = "0.000";
        [Parameter]
        public string TiltCommand { get; set; } = "0.000";
        
        [Parameter]
        public string TiltCurrent { get; set; } = "0.000";
        
        [Parameter]
        public string AzimuthSpeed { get; set; } = "0.000";
        [Parameter]
        public string ElevationSpeed { get; set; } = "0.000";
        [Parameter]
        public string TiltSpeed { get; set; } = "0.000";

        protected override async Task OnAfterRenderAsync(bool firstRender)
        {
            if (firstRender)
            {
                // 初始化定时器更新时间
                _timer = new System.Timers.Timer(1000);
                _timer.Elapsed += async (sender, e) =>
                {
                    await UpdateCurrentTime();
                };
                _timer.Start();

                // 初始更新时间
                await UpdateCurrentTime();
            }
        }

        private async Task UpdateCurrentTime()
        {
            try
            {
                var now = DateTime.Now;
                CurrentTime = now.ToString("yyyy年MM月dd日 HH:mm:ss");
                
                // 通知UI更新
                await InvokeAsync(StateHasChanged);
            }
            catch (Exception)
            {
                // 忽略异常，避免应用崩溃
            }
        }

        public void Dispose()
        {
            _timer?.Stop();
            _timer?.Dispose();
        }
    }
}